//
//  AppDelegate.m
//  AFNetworkDemo
//
//  Created by yhs on 16/9/10.
//  Copyright © 2016年 yhs. All rights reserved.
//

#import "AppDelegate.h"
#import "AFNetworking.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //GET 请求
//    [self getRequest];
    
    //POST 请求
//    [self postRequest];
    
    //AFN 下载
//    [self downLoad];
    
    //AFN 上传
//    [self upLoad];
    
    //监听网络状态
    [self AFNetworkStatus];
    
    return YES;
}

#pragma mark GET请求
-(void)getRequest
{
    //GET 请求
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *urlString = @"http://api.k780.com:88/?app=weather.today&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
    //返回数据 text/html时 发生错误
    [manager GET:urlString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        //???
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //do something()成功回调
        NSLog(@"发送成功 %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //错误回调
        NSLog(@"%@",error);
    }];
}

#pragma mark POST请求
-(void)postRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //POST 请求
    NSDictionary *parameters = @{@"zhangsan":@"138", @"lishi":@"150"};
    NSString *urlString = @"http://api.k780.com:88/?app=weather.today&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
    
    [manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        //??....
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //接受成功
        NSLog(@"接受成功   %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //error
        NSLog(@"%@", error);
    }];
}

#pragma mark 下载
-(void)downLoad
{
    //1. 创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.创建URL
    NSURL *url  = [NSURL URLWithString:@"http://www.baidu.com"];
    
    //3.创建request
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //过程
        NSLog(@"%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //目标URL(存储)
        NSLog(@"默认下载地址 %@", targetPath);
        
        //设置下载路径
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        
        NSLog(@"设置下载地址 %@", targetPath);
        return [NSURL URLWithString:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        //下载完成
        NSLog(@"下载完成");
        NSLog(@"%@-----%@", response, filePath);
        
    }];
    
    [task resume];
}

#pragma mark 上传
/**
 *  AFN 3.0 上传
 *      有两种方式
 *          upLoad1 和 upLoad2
 */
-(void)upLoad
{
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.url path
    NSString *urlString = @"";
    NSDictionary *dict = @{@"username":@"yhs"};
    
   [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
       //上传文件参数
       //方法一
       UIImage *image = [UIImage imageNamed:@"123.png"];
       NSData *data = UIImagePNGRepresentation(image);
       
       [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
       
       //方法二
//       [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"file" fileName:@"1234.png" mimeType:@"application/octet-stream" error:nil];
   } progress:^(NSProgress * _Nonnull uploadProgress) {
       //过程
       NSLog(@"长传进度  %lf", 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       //上传成功
       NSLog(@"上传成功 %@", responseObject);
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       //发生错误
       NSLog(@"上传失败 %@", error);
   }];
}

#pragma mark 监测当前网络状态（网络监听）
-(void)AFNetworkStatus
{
    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,      未知
     AFNetworkReachabilityStatusNotReachable     = 0,       无网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络状态");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据网");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi网络");
                break;
                
            default:
                break;
        }
        
    }] ;

    
}

- (void)applicationWillResignActive:(UIApplication *)application
{
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
}

- (void)applicationWillTerminate:(UIApplication *)application
{
}

@end
